package com.ruint.core.utils.volley;

import java.io.UnsupportedEncodingException;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.JsonSyntaxException;
import com.ruint.core.utils.preferences.CorePreferences;

/**
 * Wrapper for Volley requests to facilitate parsing of json responses.
 * 
 * @param <T>
 */
public class OmniRequest extends Request<String> {

  /**
   * Callback for response delivery
   */
  private final Listener<String> mListener;

  private String url;

  /**
   * @param method
   *          Request type.. Method.GET etc
   * @param url
   *          path for the requests
   * @param objectClass
   *          expected class type for the response. Used by gson for
   *          serialization.
   * @param listener
   *          handler for the response
   * @param errorListener
   *          handler for errors
   */
  public OmniRequest(String url, Listener<String> listener, ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.url = url;
    this.mListener = listener;
  }

  @Override
  protected Response<String> parseNetworkResponse(NetworkResponse response) {
    CorePreferences.DEBUG("request:" + url);
    CorePreferences.DEBUG("result took time:" + response.networkTimeMs + "ms");
    try {
      String result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
      CorePreferences.DEBUG("result:" + result);
      return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
      return Response.error(new ParseError(e));
    } catch (JsonSyntaxException e) {
      return Response.error(new ParseError(e));
    }
  }

  @Override
  protected void deliverResponse(String response) {
    mListener.onResponse(response);
  }

}
